<template>
  <div style="display: flex; flex-direction: column; flex: 1">
    <div class="app-container" v-if="codedetail">
      <div class="app-container-inner">
        <div class="header">
          <div style="display: flex; align-items: center; gap: 5px">
            <span style="font-size: 14px; font-weight: bold">一物一码：</span>
            <span style="font-size: 14px; font-weight: bold">{{ codedetail.securityCode }}</span>
            <HStatus type="info" v-if="codedetail.status === 1">未质保</HStatus>
            <HStatus v-if="codedetail.status === 2">质保中</HStatus>
            <HStatus type="warning" v-if="codedetail.status === 3">已过保</HStatus>
            <HStatus type="error" v-if="codedetail.status === 4">已作废</HStatus>
            <HStatus v-if="codedetail.type === 1">成品</HStatus>
            <HStatus type="warning" v-else>配件</HStatus>
          </div>
          <div style="display: flex; gap: 5px">
            <HPlainButton @click="changeuserRegister" v-if="codedetail.status != 1"
              >变更登记地址</HPlainButton
            >
            <HPlainButton v-if="codedetail.register" @click="Changecustomer">变更客户</HPlainButton>
            <router-link to="/order/new">
              <HPlainButton>新建工单</HPlainButton>
            </router-link>
            <HPlainButton v-if="!codedetail.register" @click="changeInf">修改信息</HPlainButton>
            <HPlainButton @click="userRegister" v-if="codedetail.status == 1"
              >登记客户</HPlainButton
            >

            <HPlainButton @click="activeOpen" v-if="!codedetail.activa">手动激活</HPlainButton>
            <HPlainButton type="error" v-if="!codedetail.activa" @click="deleCo"
              >删除编码</HPlainButton
            >
          </div>
        </div>
      </div>
    </div>
    <!-- 基本信息 -->
    <div class="app-container" v-loading="loading" element-loading-text="加载中...">
      <div class="app-container-inner" v-if="codedetail">
        <h4 class="title_bl">基本信息</h4>
        <el-form label-width="60px" class="basic_information">
          <el-row>
            <el-col :lg="6" :sm="12">
              <el-form-item label="产品品牌">
                <span class="ml">{{ codedetail.brand }}</span>
              </el-form-item>
              <el-form-item label="产品型号">
                <span class="ml">{{ codedetail.model }}</span>
              </el-form-item>
              <el-form-item label="产品规格">
                <span class="ml">{{ codedetail.goodsSpecName }}</span>
              </el-form-item>
            </el-col>
            <el-col :lg="6" :sm="12">
              <el-form-item label="编码状态">
                <HStatus type="info" v-if="codedetail.status == 1">
                  <span style="font-size: 12px">未质保</span>
                </HStatus>
                <HStatus v-if="codedetail.status == 2">
                  <span style="font-size: 12px">质保中</span>
                </HStatus>
                <HStatus type="info" v-if="codedetail.status == 3">
                  <span style="font-size: 12px">已过保</span>
                </HStatus>
                <HStatus type="error" v-if="codedetail.status == 4">
                  <span style="font-size: 12px">已作废</span>
                </HStatus>
              </el-form-item>
              <el-form-item label="是否激活">
                <HStatus type="success" v-if="codedetail.activa">
                  <span style="font-size: 12px">已激活</span>
                </HStatus>
                <HStatus type="info" v-else>
                  <span style="font-size: 12px">未激活</span>
                </HStatus>
              </el-form-item>
              <el-form-item label="激活日期">
                <span class="ml">{{ codedetail.activaTime }}</span>
              </el-form-item>
            </el-col>
            <el-col :lg="6" :sm="12">
              <el-form-item label="所属客户">
                <span class="ml">{{ codedetail.username }}</span>
              </el-form-item>
              <el-form-item label="联系手机">
                <span class="ml">{{ codedetail.phone }}</span>
              </el-form-item>
              <el-form-item label="登记地址">
                <span class="ml"
                  >{{ codedetail.province }}{{ codedetail.city }}{{ codedetail.area
                  }}{{ codedetail.town }}{{ codedetail.address }}</span
                >
              </el-form-item>
            </el-col>
            <el-col :lg="6" :sm="12">
              <el-form-item label="创建人员">
                <span class="ml">{{ codedetail.createEmp }}</span>
              </el-form-item>
              <el-form-item label="创建时间">
                <span class="ml">{{ codedetail.createTime }}</span>
              </el-form-item>
              <el-form-item label="更新时间">
                <span class="ml">{{ codedetail.updateTime }}</span>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </div>
    </div>
    <el-container v-if="codedetail">
      <div class="coded_message">
        <el-aside width="230px">
          <h4 class="title">编码信息</h4>
          <el-form label-width="80px" class="form_list">
            <p class="bor_link"></p>
            <el-form-item label="一物一码">
              <span>{{ codedetail.securityCode }}</span>
            </el-form-item>
            <el-form-item label="批次编码">
              <span>{{ codedetail.batchCode }}</span>
            </el-form-item>
            <el-form-item label="商品类型">
              <span v-if="codedetail.type == 1">成品</span>
              <span v-else>配件</span>
            </el-form-item>
            <el-form-item label="质保开始">
              <span>{{ codedetail.warrantyStartTime }}</span>
            </el-form-item>
            <el-form-item label="质保截止">
              <span>{{ codedetail.warrantyEndTime }}</span>
            </el-form-item>
            <el-form-item label="质保周期">
              <span>{{ codedetail.warrantyDay || 0 }}天</span>
            </el-form-item>
            <el-form-item label="首次查询">
              <span>{{ codedetail.firstSelectTime }}</span>
            </el-form-item>
            <el-form-item label="最后查询">
              <span>{{ codedetail.lastSelectTime }}</span>
            </el-form-item>
            <el-form-item label="查询次数">
              <span>{{ codedetail.selectNum }}</span>
            </el-form-item>
            <el-form-item label="编码来源">
              <span v-if="codedetail.codeSource == 1">系统创建</span>
              <span v-if="codedetail.codeSource == 2">系统导入</span>
              <span v-if="codedetail.codeSource == 3">工单报单创建</span>
              <span v-if="codedetail.codeSource == 4">第三方系统编码</span>
            </el-form-item>
            <p class="bor_link"></p>
            <el-form-item label="仓储编码">
              <span>{{ codedetail.storeCode }}</span>
            </el-form-item>
            <el-form-item label="出库状态">
              <HStatus type="info" v-if="codedetail.storeStatus === 1">未出入库</HStatus>
              <HStatus type="warning" v-if="codedetail.storeStatus === 2">预入库</HStatus>
              <HStatus type="success" v-if="codedetail.storeStatus === 3">已入库</HStatus>
              <HStatus type="warning" v-if="codedetail.storeStatus === 4">预出库</HStatus>
              <HStatus type="success" v-if="codedetail.storeStatus === 5">已出库</HStatus>
            </el-form-item>
            <el-form-item label="入库单号">
              <span>{{ codedetail.inboundCode }}</span>
            </el-form-item>
            <el-form-item label="出库单号">
              <span>{{ codedetail.outboundCode }}</span>
            </el-form-item>
            <el-form-item label="入库时间">
              <span>{{ codedetail.inboundTime }}</span>
            </el-form-item>
            <el-form-item label="出库时间">
              <span>{{ codedetail.outboundTime }}</span>
            </el-form-item>
          </el-form>
        </el-aside>
      </div>
      <el-main>
        <div class="list_tabs">
          <el-tabs
            class="tabs_height"
            v-model="activeName"
            @tab-change="activeNameChange"
            v-loading="loadingtabs"
            element-loading-text="加载中..."
          >
            <!-- 历史工单 -->
            <el-tab-pane label="历史工单" name="first">
              <el-table
                stripe
                resizable
                :data="historyOrder"
                :border="true"
                style="width: 100%; position: absolute"
                height="100%"
              >
                <template #empty>
                  <el-empty description="暂无数据" />
                </template>
                <el-table-column
                  type="index"
                  label="序号"
                  fixed="left"
                  width="50"
                ></el-table-column>
                <el-table-column
                  prop="orderNo"
                  show-overflow-tooltip
                  label="工单编号"
                  width="150px"
                >
                  <template v-slot="item">
                    <span
                      class="xy_main_btn"
                      @click="router.push('/order/odetail/' + item.row.id)"
                      >{{ item.row.orderNo }}</span
                    >
                  </template>
                </el-table-column>
                <el-table-column prop="status" show-overflow-tooltip label="工单状态" width="100px">
                  <template v-slot="scope">
                    <HStatus type="warning" v-if="scope.row.status === 1">待派单</HStatus>
                    <HStatus type="warning" v-if="scope.row.status === 2">待服务商确认</HStatus>
                    <HStatus type="warning" v-if="scope.row.status === 3">处理中</HStatus>
                    <HStatus type="success" v-if="scope.row.status === 4">已完成</HStatus>
                    <HStatus type="info" v-if="scope.row.status === 5">已取消</HStatus>
                  </template>
                </el-table-column>
                <el-table-column prop="workLevel" label="等级" width="90px">
                  <template v-slot="item">
                    <span :style="{ color: item.row.workLevelColor }">{{
                      item.row.workLevel
                    }}</span>
                  </template>
                </el-table-column>
                <el-table-column prop="totalPrice" label="工单费用" width="90px" align="center">
                  <template v-slot="item">
                    <span>￥{{ (item.row.totalPrice || 0).toFixed(2) }}</span>
                  </template>
                </el-table-column>
                <el-table-column
                  prop="username"
                  show-overflow-tooltip
                  label="客户名称"
                  width="130"
                />
                <el-table-column prop="phone" label="客户手机号" width="140" />
                <el-table-column
                  prop="network"
                  show-overflow-tooltip
                  label="服务商"
                  width="130px"
                />
                <el-table-column prop="updateTime" label="最后更新" width="130px" />
              </el-table>
            </el-tab-pane>

            <!-- 变更客户记录 -->
            <el-tab-pane label="变更客户记录" name="second">
              <el-table
                stripe
                resizable
                :border="true"
                :data="userchangeLOgData"
                style="width: 100%; position: absolute"
                height="100%"
              >
                <template #empty>
                  <el-empty description="暂无数据" />
                </template>
                <el-table-column
                  prop="count"
                  label="变更次数"
                  width="80"
                  fixed
                  show-overflow-tooltip
                >
                  <template v-slot="item">
                    <div class="change_alter">
                      <span>{{ item.row.count }}</span>
                      <img
                        src="../../../../assets/image/zhanpai.png"
                        class="img_zhankai"
                        @click="gochangeDetail(item.row)"
                        alt="#"
                      />
                    </div>
                  </template>
                </el-table-column>
                <el-table-column
                  prop="goodsName"
                  show-overflow-tooltip
                  label="商品名称"
                  width="290"
                >
                  <div>
                    {{ codedetail.brand }} &nbsp; {{ codedetail.goodsName }} &nbsp;
                    {{ codedetail.model }} &nbsp;
                    {{ codedetail.goodsSpecName }}
                  </div>
                </el-table-column>
                <el-table-column prop="username" show-overflow-tooltip label="所属客户" width="140">
                  <div> </div>
                </el-table-column>
                <el-table-column prop="phone" show-overflow-tooltip label="联系手机" width="140">
                  <div> </div>
                </el-table-column>
                <el-table-column prop="address" show-overflow-tooltip label="地址" width="140">
                  <template v-slot="item">
                    {{ item.row.province }} {{ item.row.city }} {{ item.row.area }}
                    {{ item.row.town }} {{ item.row.address }}
                  </template>
                </el-table-column>
                <el-table-column prop="" show-overflow-tooltip label="附件" width="140">
                  <div> </div>
                </el-table-column>
                <el-table-column prop="createEmp" show-overflow-tooltip label="操作人" width="140">
                </el-table-column>
                <el-table-column
                  prop="createTime"
                  show-overflow-tooltip
                  label="操作时间"
                  width="140"
                >
                </el-table-column>
              </el-table>
              <div class="footer">
                <Pagination
                  ref="paginDom"
                  :list_total="total"
                  @size-change="activeNameChange('second')"
                  @current-change="activeNameChange('second')"
                />
              </div>
            </el-tab-pane>
            <!-- 产品溯源 -->
            <el-tab-pane label="产品溯源" name="third">
              <el-table
                stripe
                resizable
                :border="true"
                :data="changeLOgData"
                style="width: 100%; position: absolute"
                height="100%"
              >
                <template #empty>
                  <el-empty description="暂无数据" />
                </template>
                <el-table-column prop="goodsName" show-overflow-tooltip label="商品名称">
                  <template v-slot="item">
                    {{ item.row.brand }} &nbsp; {{ item.row.goodsModel }} &nbsp;
                    {{ item.row.goodsName }} &nbsp;
                    {{ item.row.goodsSpecName }}
                  </template>
                </el-table-column>
                <el-table-column prop="createEmp" show-overflow-tooltip label="操作人" width="140">
                </el-table-column>
                <el-table-column
                  prop="createTime"
                  show-overflow-tooltip
                  label="操作时间"
                  width="180"
                >
                </el-table-column>
              </el-table>
              <div class="footer">
                <Pagination
                  ref="paginDom"
                  :list_total="total"
                  @size-change="activeNameChange('second')"
                  @current-change="activeNameChange('second')"
                />
              </div>
            </el-tab-pane>
            <el-tab-pane label="操作日志" name="fourth">
              <OperationLog v-if="activeName == 'fourth'" @loading-false="loadingtabs = $event" />
            </el-tab-pane>
          </el-tabs>
        </div>
      </el-main>
    </el-container>

    <!-- 变更客户弹窗 -->
    <HModal v-model="changeCustomerModalVisible" title="变更客户" :width="800">
      <ChangeCustomer
        ref="changeCustomer"
        @close-popup="changeCustomerModalVisible = $event"
        :codedetail="codedetail"
      />
    </HModal>

    <!-- 修改编码信息弹窗 -->
    <HModal v-model="changeDialog" title="修改编码信息" :width="450">
      <el-form class="cards">
        <div class="modal_form_content">
          <el-form-item label="当前信息">
            <div class="current_info">
              <span>品牌：{{ codedetail.brand }}</span>
              <span>商品名称：{{ codedetail.goodsName }}</span>
              <span>商品型号：{{ codedetail.model }}</span>
              <span>商品规格：{{ codedetail.goodsSpecName }}</span>
            </div>
          </el-form-item>
          <el-form-item label="编码类型" class="form_radio_group_item">
            <el-radio-group v-model="dataInfForm.type" @change="changeSwitch('')">
              <el-radio :value="1" :disabled="dataInfForm.type == 2">成品</el-radio>
              <el-radio :value="2" :disabled="dataInfForm.type == 1">配件</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="新的型号" class="form_select_item">
            <el-select
              v-model="dataInfForm.goodsId"
              class="select_item"
              remote-show-suffix
              :filter-method="remoteMethod2"
              :loading="loading3"
              placeholder="请选择"
              filterable
              clearable
              @change="seleSwitch('')"
            >
              <el-option
                :disabled="item.model == codedetail.model"
                v-for="item in options"
                :key="item.id"
                :value="item.id"
                :label="item.model"
                class="left12"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="规格信息" class="form_select_item">
            <el-select
              v-model="dataInfForm.goodsSpecId"
              remote-show-suffix
              :filter-method="remoteMethod3"
              :loading="loading4"
              class="select_item"
              placeholder="请选择"
              filterable
              clearable
            >
              <el-option
                v-for="item in options2"
                :key="item.id"
                :value="item.id"
                :label="item.name"
                class="left12"
              />
            </el-select>
          </el-form-item>
        </div>
      </el-form>
      <template #footerRight>
        <HButton is-modal type="primary" @click="onSvaeInf">保存</HButton>
        <HButton is-modal @click="changeDialog = false">取消</HButton>
      </template>
    </HModal>

    <!-- 登记用户弹窗 -->
    <HModal v-model="checkDialog" title="登记用户" :width="450">
      <el-form
        class="modal_form_content"
        label-width="80px"
        ref="formRef"
        :model="userForm"
        :rules="rules"
      >
        <!-- 关联用户 -->
        <el-form-item label="关联用户" class="form_select_item">
          <el-select
            v-model="value4"
            placeholder="请选择关联用户"
            filterable
            clearable
            @change="changeSel"
            remote-show-suffix
            :filter-method="remoteMethod"
            :loading="loading2"
            class="select_item"
          >
            <el-option
              v-for="item in relevanceUser"
              :key="item.id"
              :value="item.id"
              :label="item.name + ' ' + item.phone"
              @click="getinformation(item)"
            />
          </el-select>
        </el-form-item>

        <!-- 登记姓名 -->
        <el-form-item label="登记姓名" prop="name" class="form_input_item">
          <el-input v-model="userForm.name" clearable placeholder="请输姓名" />
        </el-form-item>

        <!-- 登记号码 -->
        <el-form-item label="登记号码" prop="phone" class="form_input_item">
          <el-input v-model="userForm.phone" clearable placeholder="请输登记号码" />
        </el-form-item>

        <!-- 用户地址 -->
        <el-form-item label="用户地址" class="form_select_item">
          <SingleAddress
            ref="addrsDom"
            @value-change="handleAddressChange"
            :addrs_data="userForm.adds"
          />
        </el-form-item>

        <!-- 详细地址 -->
        <el-form-item label="详细地址" prop="address" class="form_input_item">
          <el-input
            v-model="userForm.address"
            placeholder="请输入详细地址"
            clearable
            maxlength="200"
          />
        </el-form-item>
      </el-form>
      <template #footerRight>
        <HButton is-modal type="primary" @click="onsaveCodeRegister">保存</HButton>
        <HButton is-modal @click="checkDialog = false">取消</HButton>
      </template>
    </HModal>

    <!-- 变更登记地址 -->
    <HModal v-model="checkDialogAddress" title="变更登记地址" size="small">
      <el-form
        class="modal_form_content"
        label-width="80px"
        ref="formRef"
        :model="userchangeForm"
        :rules="rules"
      >
        <el-form-item label="用户地址" class="form_select_item">
          <SingleAddress
            ref="addrsDom2"
            @value-change="handleChangeUserFormAddress"
            :address="userchangeForm.adds"
          />
        </el-form-item>
        <el-form-item label="详细地址" prop="address" class="form_input_item">
          <el-input
            v-model="userchangeForm.address"
            placeholder="请输入详细地址"
            class="input-width"
            clearable
            maxlength="200"
          />
        </el-form-item>
      </el-form>
      <template #footerRight>
        <HButton type="primary" is-modal @click="userRegisterAddress">保存</HButton>
        <HButton is-modal @click="checkDialogAddress = false">取消</HButton>
      </template>
    </HModal>

    <!-- 变更记录详情弹窗 -->
    <el-drawer v-model="changeDetail" :show-close="false">
      <template #header="{ close, titleId, titleClass }">
        <h4 :id="titleId" :class="titleClass">变更历史</h4>
        <span class="dialog-footer">
          <el-button @click="close" class="btn_dialog_Cancel">取消</el-button></span
        >
      </template>
      <change-popup :LOgData="LOgData" :codedetail="codedetail"></change-popup>
    </el-drawer>
  </div>
</template>

<script setup lang="ts">
  import { ref, onMounted, reactive, watch } from 'vue'
  import { useRouter, useRoute } from 'vue-router'
  import { ElMessage, ElMessageBox } from 'element-plus'
  import ChangePopup from './components/changePopup/index.vue'
  import ChangeCustomer from './components/changeCustomer/index.vue'
  import {
    getInfo,
    activCode,
    updateCodeRegisterAddress,
    userChangeList,
    codeGoodsChangeLog,
    deleteCode,
    saveCodeRegister,
    productSpecPageSelect,
    spareSpecPageSelect,
    selecUser,
    codeGoodsBindingChange,
    productPageSelect,
    sparePageSelect,
    getHistoryOrderList,
  } from '@/api/code'
  import SingleAddress from '@/components/address/singleAddress.vue'
  import OperationLog from './components/operationLog/index.vue'
  import { phone } from '@/utils/validate'
  import type { FormInstance } from 'element-plus'
  import Pagination from '@/components/Pagination/index.vue'
  import _ from 'lodash'
  import HStatus from '@/components/common/status/HStatus.vue'
  import HPlainButton from '@/components/common/button/HPlainButton.vue'
  import HButton from '@/components/common/button/HButton.vue'
  import HModal from '@/components/common/Modal/HModal.vue'
  import pageComponentName from '@/config/page-component-name'

  defineOptions({
    name: pageComponentName.snCode.snCodeDetail,
  })

  const formRef = ref<FormInstance | null>(null)
  const router = useRouter()
  const route = useRoute()
  const value4 = ref('')
  const loading2 = ref(false)
  const loading3 = ref(false)
  const loading4 = ref(false)
  const changeDialog = ref(false)
  const checkDialog = ref(false)
  const activeName = ref('first')
  const changeDetail = ref(false)
  const changeCustomerModalVisible = ref(false)
  const codedetail = ref(null)
  const loading = ref(true)
  const addrsDom = ref<InstanceType<typeof SingleAddress> | null>(null) //登记地址dom
  const addrsDom2 = ref() //变更登记地址dom
  const paginDom = ref()
  const total = ref(0)
  const relevanceUser = ref()
  const dataPage = {
    limit: 0,
    name: '',
    page: 0,
  }
  const checkDialogAddress = ref(false) //变更登记地址
  const LOgData = ref()
  const userchangeLOgData = ref(null)
  const changeLOgData = ref(null) //变更记录数据
  const loadingtabs = ref(false)
  const historyOrder = ref([]) // 历史工单对象
  const dataInfForm = reactive({
    goodsId: null,
    goodsSpecId: null,
    id: null,
    remark: '',
    tableType: route.params.tableType,
    type: null,
  })
  const userForm = reactive({
    address: '',
    area: '',
    city: '',
    id: null,
    name: '',
    phone: '',
    province: '',
    town: '',
    userId: '',
    adds: {
      province: '',
      area: '',
      city: '',
      town: '',
    },
  })
  const userchangeForm = reactive({
    address: '',
    area: '',
    city: '',
    province: '',
    town: '',
    adds: {
      province: '',
      area: '',
      city: '',
      town: '',
    },
  })
  const gochangeDetail = (val) => {
    changeDetail.value = true
    LOgData.value = val
  }
  // 验证规则
  const rules = reactive({
    phone: [
      { required: false, trigger: 'blur' },
      { validator: phone(userForm.phone), trigger: 'change' },
    ],
  })
  const changeSel = (val) => {
    userForm.userId = val
  }
  const remoteMethod = _.throttle((val: string) => {
    if (dataPage.name !== val) {
      dataPage.name = val
      loading2.value = true
      selecUser(dataPage).then((res) => {
        relevanceUser.value = res.data.data.rows
        loading2.value = false
      })
    }
  }, 500)

  const remoteMethod2 = _.throttle((val: string) => {
    loading3.value = true
    changeSwitch(val)
  }, 500)

  // 点击关联用户
  const getinformation = (val) => {
    userForm.userId = val.id
    userForm.address = val.address
    userForm.area = val.area
    userForm.city = val.city
    userForm.name = val.name
    userForm.phone = val.phone
    userForm.province = val.province
    userForm.town = val.town
    userForm.adds = null
    userForm.adds = {
      province: val.province,
      area: val.area,
      city: val.city,
      town: val.town,
    }
  }
  // 手动激活
  const activeOpen = () => {
    ElMessageBox.confirm('是否激活该编码?', '提示', {
      draggable: true,
      cancelButtonText: '否',
      confirmButtonText: '是',
      type: 'warning',
      autofocus: false,
    }).then(() => {
      var data = [
        {
          id: codedetail.value.id,
          tableType: route.params.tableType,
        },
      ]
      activCode(data).then((res) => {
        if (res.data.code == 20000) {
          ElMessage({
            message: res.data.message,
            type: 'success',
            duration: 4000,
          })
          getDetail()
        } else {
          if (res.data.isError)
            ElMessage({
              message: res.data.message,
              type: 'error',
              duration: 4000,
            })
        }
      })
    })
  }
  const Changecustomer = () => {
    changeCustomerModalVisible.value = true
  }
  // 删除编码
  const deleCo = () => {
    ElMessageBox.confirm('是否删除该编码?', '提示', {
      draggable: true,
      cancelButtonText: '否',
      confirmButtonText: '是',
      type: 'warning',
      autofocus: false,
    }).then(async () => {
      var data = [
        {
          id: codedetail.value.id,
          tableType: route.params.tableType,
        },
      ]
      const res = await deleteCode(data)
      if (res.data.code == 20000) {
        ElMessage({
          message: res.data.message,
          type: 'success',
        })
        router.push({ path: '/code/list' })
      } else {
        if (res.data.isError)
          ElMessage({
            message: res.data.message,
            type: 'error',
          })
      }
    })
  }
  // 点击登记用户弹出
  const userRegister = () => {
    if (codedetail.value.status != 1) {
      userForm.id = codedetail.value.id
    }
    checkDialog.value = true
    userForm.address = codedetail.value.address
    userForm.area = codedetail.value.area
    userForm.city = codedetail.value.city
    userForm.name = codedetail.value.username
    userForm.phone = codedetail.value.phone
    userForm.province = codedetail.value.province
    userForm.town = codedetail.value.town
    userForm.adds = {
      province: codedetail.value.province,
      area: codedetail.value.area,
      city: codedetail.value.city,
      town: codedetail.value.town,
    }

    selecUser(dataPage).then((res) => {
      relevanceUser.value = res.data.data.rows
    })
  }
  // 变更登记地址弹窗
  const changeuserRegister = () => {
    checkDialogAddress.value = true
  }

  // 变更地址更新事件
  const handleChangeUserFormAddress = () => {
    if (addrsDom2.value) {
      const address = addrsDom2.value.getSelectAddr()
      userchangeForm.province = address.province
      userchangeForm.area = address.area
      userchangeForm.city = address.city
      userchangeForm.town = address.town
    }
  }

  // 保存变更登记地址
  const userRegisterAddress = () => {
    updateCodeRegisterAddress({ ...userchangeForm }, codedetail.value.id).then((res) => {
      if (res.data.code == 20000) {
        checkDialogAddress.value = false
        ElMessage({
          message: res.data.message,
          type: 'success',
          duration: 4500,
        })
        getDetail()
      } else {
        if (res.data.isError)
          ElMessage({
            message: res.data.message,
            type: 'error',
            duration: 4500,
          })
      }
    })
  }

  const options = ref()
  const options2 = ref()

  // 地址更新事件
  const handleAddressChange = () => {
    if (addrsDom.value) {
      const address = addrsDom.value.getSelectAddr()
      userForm.province = address.province
      userForm.area = address.area
      userForm.city = address.city
      userForm.town = address.town
    }
  }

  // 保存登记用户
  const onsaveCodeRegister = () => {
    saveCodeRegister({ ...userForm }, route.params.id).then((res) => {
      if (res.data.code == 20000) {
        checkDialog.value = false
        ElMessage({
          message: res.data.message,
          type: 'success',
          duration: 4500,
        })
        getDetail()
      } else {
        if (res.data.isError)
          ElMessage({
            message: res.data.message,
            type: 'error',
            duration: 4500,
          })
      }
    })
  }
  // 监听编码类型
  watch(
    () => dataInfForm.type,
    () => {
      dataInfForm.goodsId = null
      dataInfForm.goodsSpecId = null
    },
  )
  watch(
    () => dataInfForm.goodsId,
    () => {
      dataInfForm.goodsSpecId = null
    },
  )
  onMounted(async () => {
    await getDetail()
    await getHistoryOrderListApi()
  })
  // 编码详情
  const getDetail = async () => {
    loading.value = true
    const res = await getInfo(route.params.id)
    if (res.data.code == 20000) {
      codedetail.value = res.data.data.row
      loading.value = false
    } else {
      if (res.data.isError)
        ElMessage({
          message: res.data.message,
          type: 'error',
          duration: 5000,
        })
    }
  }
  // 修改信息弹窗
  const changeInf = () => {
    changeDialog.value = true
    dataInfForm.type = codedetail.value.type
    dataInfForm.id = codedetail.value.id
    changeSwitch('')
  }
  // 修改编码信息弹窗 =>编码类型选择变换
  const changeSwitch = async (val: string) => {
    let data = {
      limit: 0,
      name: val,
      page: 0,
    }
    if (dataInfForm.type == 1) {
      const res = await productPageSelect(data)
      if (res.data.code == 20000) {
        options.value = res.data.data.rows
      }
      loading3.value = false
    } else {
      const res = await sparePageSelect(data)
      if (res.data.code == 20000) {
        options.value = res.data.data.rows
      }
      loading3.value = false
    }
  }
  // 修改信息保存
  const onSvaeInf = () => {
    codeGoodsBindingChange(dataInfForm).then((res) => {
      if (res.data.code == 20000) {
        changeDialog.value = false
        ElMessage({
          message: res.data.message,
          type: 'success',
          duration: 5000,
        })
        getDetail()
      } else {
        ElMessage({
          message: res.data.message,
          type: 'error',
          duration: 5000,
        })
      }
    })
  }
  const remoteMethod3 = _.throttle((val: string) => {
    seleSwitch(val)
  }, 500)
  // 修改编码信息弹窗 =>型号选择变换
  const seleSwitch = async (val: string) => {
    let data = {
      limit: 0,
      name: val,
      page: 0,
    }
    if (!dataInfForm.goodsId) {
      return
    }
    if (dataInfForm.type == 1) {
      const res = await productSpecPageSelect(data, dataInfForm.goodsId)
      if (res.data.code == 20000) {
        options2.value = res.data.data.rows
      }
      loading4.value = false
    } else {
      const res = await spareSpecPageSelect(data, dataInfForm.goodsId)
      if (res.data.code == 20000) {
        options2.value = res.data.data.rows
      }
      loading4.value = false
    }
  }

  // 历史工单
  const getHistoryOrderListApi = async () => {
    const page = {
      page: 0,
      limit: 50,
    }
    historyOrder.value = []
    const res = await getHistoryOrderList(route.params.id, page)
    historyOrder.value = res.data.data.rows
  }
  // first历史工单 second变更记录 third操作日志
  const activeNameChange = (val) => {
    let data = {
      limit: 0,
      page: 0,
    }
    loadingtabs.value = true
    switch (val) {
      // 历史工单
      case 'first':
        getHistoryOrderListApi()
        loadingtabs.value = false
        break
      case 'second':
        // 变更客户记录
        userChangeList(data, route.params.id).then((res) => {
          if (res.data.code == 20000) {
            userchangeLOgData.value = res.data.data.rows
            total.value = Number(res.data.data.total)
          } else {
            if (res.data.isError)
              ElMessage({
                message: res.data.message,
                type: 'error',
                duration: 5000,
              })
          }
          loadingtabs.value = false
        })
        break
      case 'third':
        // 产品溯源
        codeGoodsChangeLog(data, route.params.id).then((res) => {
          if (res.data.code == 20000) {
            changeLOgData.value = res.data.data.rows
            total.value = Number(res.data.data.total)
          } else {
            if (res.data.isError)
              ElMessage({
                message: res.data.message,
                type: 'error',
                duration: 5000,
              })
          }
          loadingtabs.value = false
        })
        break
      default:
        break
    }
  }
</script>

<style scoped lang="scss">
  @import './index';
</style>
